
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <netdb.h>

#define BUFLEN 512

/*
 * Example:
 *
 * client 50000 "PUT:key1:value1"
 *
 * valid commands:
 * PUT, GET, END, QUERY
 *
 *  Syntax: ./client portnumber command
 */

int main(int argc, char *argv[]) {
	struct sockaddr_in sr;
	int s, i, slen = sizeof(sr);
	char buf[BUFLEN];
	struct hostent *hent;

	int portnum;

	if (argc != 3) {
		printf("Correct syntax: %s <portnum> <message>", argv[0]);
		return 1;
	}

	portnum = atoi(argv[1]);
	strcpy(buf, argv[2]);

	hent = gethostbyname("localhost");
	if(hent == NULL)
	{	printf("gethostbyname failed ");
		exit(1);
	}

	if ((s = socket(AF_INET, SOCK_STREAM, 0)) == -1) {}

	memset((char *) &sr, 0, sizeof(sr));
	sr.sin_family = AF_INET;
	sr.sin_port = htons(portnum);
	sr.sin_addr = *(struct in_addr*)(hent ->h_addr_list[0]);

	if (connect(s, (struct sockaddr *) &sr, sizeof(sr)) == -1) {
		printf("connect error");
		exit(1);
	}

	/* send a message to the server PORT on machine HOST */
	if (send(s, buf, BUFLEN, 0) == -1) {
		printf("send error");
		exit(1);
	}
	
	close(s);
	
	//If this is a GET message, then listen for a response from the node that finds it
	char *command = strtok(buf, ":");
	if(strcmp(command, "GET") == 0){
		struct sockaddr_in sock_server, sock_client;
		int servSocket, socketlen = sizeof(sock_client);
		int client;
		
		if ((servSocket = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
			printf("error in socket creation");
			exit(1);
		}
		
		memset((char *) &sock_server, 0, sizeof(sock_server));
		sock_server.sin_family = AF_INET;
		int port = 65534;
		sock_server.sin_port = htons(port);
		sock_server.sin_addr.s_addr = htonl(INADDR_ANY);
		if (bind(servSocket, (struct sockaddr *) &sock_server, sizeof(sock_server)) == -1) {
			printf("error in binding socket");
			exit(1);
		}

		if (listen(servSocket, 10) == -1) {
			printf("listen error");
			exit(1);
		}
		
		if ((client = accept(servSocket, (struct sockaddr *) &sock_client, &socketlen)) == -1) {
			printf("accept error");
			exit(1);
		}

		if (recv(client, buf, BUFLEN, 0) == -1){
			printf("recv error");
			exit(1);
		} else if(strcmp(buf, "QUIT") == 0){
			//Node responded indicating that the key did not exist via a QUIT message, so print that and quit
			printf("Cannot get this key, does not exist!\n");
			
			close(client);
			close(servSocket);
			exit(0);
		} else{
			printf("%s\n", buf);
		}
		
		close(client);
		close(servSocket);
	}
	
	return 0;
}
